package cn.uncode.schedule.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import cn.uncode.schedule.ConsoleManager;
import cn.uncode.schedule.core.TaskDefine;
import cn.uncode.schedule.zk.TimestampTypeAdapter;


@WebServlet(name="schedule2",urlPatterns="/uncode/schedule2")
public class ManagerServlet2 extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 8160082230341182715L;
	
	private static final String UNCODE_SESSION_KEY = "uncode_key_session";
	
	private static final Gson GSON = new GsonBuilder().registerTypeAdapter(Timestamp.class,new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
	
	
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String login = (String) request.getSession().getAttribute(UNCODE_SESSION_KEY);
		response.setContentType("text/json;charset=UTF-8");
	    response.setCharacterEncoding("UTF-8");
		if(StringUtils.isBlank(login)){
			String account = request.getParameter("account");
			String password = request.getParameter("password");
			boolean avilb = false;
			try {
				avilb = ConsoleManager.getScheduleManager().checkAdminUser(account, password);
				if(avilb){
					request.getSession().setAttribute(UNCODE_SESSION_KEY, "uncode_login_success");
				}
			} catch (Exception e) {
			}
	        PrintWriter out = response.getWriter();
	        Map<String, String> rt = new HashMap<>();
	        rt.put("code", "301");
	        out.write(GSON.toJson(rt));
		}else{
			String del = request.getParameter("del");
			String start = request.getParameter("start");
			String stop = request.getParameter("stop");
			String bean = request.getParameter("bean");
			String method = request.getParameter("method");
			if(StringUtils.isNotEmpty(del)){
				TaskDefine taskDefine = new TaskDefine();
				String[] dels = del.split("_");
				taskDefine.setTargetBean(dels[0]);
				taskDefine.setTargetMethod(dels[1]);
				if(dels.length > 2){
					taskDefine.setExtKeySuffix(dels[2]);
				}
				ConsoleManager.delScheduleTask(taskDefine);
			}else if(StringUtils.isNotEmpty(start)){
				TaskDefine taskDefine = new TaskDefine();
				String[] dels = start.split("_");
				taskDefine.setTargetBean(dels[0]);
				taskDefine.setTargetMethod(dels[1]);
				if(dels.length > 2){
					taskDefine.setExtKeySuffix(dels[2]);
				}
				taskDefine.setStatus(TaskDefine.STATUS_RUNNING);
				ConsoleManager.updateScheduleTask(taskDefine);
			}else if(StringUtils.isNotEmpty(stop)){
				TaskDefine taskDefine = new TaskDefine();
				String[] dels = stop.split("_");
				taskDefine.setTargetBean(dels[0]);
				taskDefine.setTargetMethod(dels[1]);
				if(dels.length > 2){
					taskDefine.setExtKeySuffix(dels[2]);
				}
				taskDefine.setStatus(TaskDefine.STATUS_STOP);
				ConsoleManager.updateScheduleTask(taskDefine);
			}else if(StringUtils.isNotEmpty(bean) && StringUtils.isNotEmpty(method)){
				TaskDefine taskDefine = new TaskDefine();
				taskDefine.setTargetBean(bean);
				taskDefine.setTargetMethod(method);
				String before = request.getParameter("before");
				if(StringUtils.isNotBlank(before)){
					taskDefine.setBeforeMethod(before);
				}
				String after = request.getParameter("after");
				if(StringUtils.isNotBlank(after)){
					taskDefine.setAfterMethod(after);
				}
				String threadNum = request.getParameter("threadNum");
				int num = 0;
				if(StringUtils.isNotBlank(threadNum)){
					num = Integer.parseInt(threadNum);
					taskDefine.setThreadNum(num);
				}
				String type = request.getParameter("type");
				if(StringUtils.isNotBlank(type)){
					if(TaskDefine.TYPE_UNCODE_MULTI_MAIN_TASK.equals(type)){
						taskDefine.setType(TaskDefine.TYPE_UNCODE_MULTI_MAIN_TASK);
					}else if(TaskDefine.TYPE_UNCODE_SINGLE_TASK.equals(type)){
						taskDefine.setType(TaskDefine.TYPE_UNCODE_SINGLE_TASK);
					}
				}else{
					if(num > 1){
						taskDefine.setType(TaskDefine.TYPE_UNCODE_MULTI_MAIN_TASK);
					}else{
						taskDefine.setType(TaskDefine.TYPE_UNCODE_SINGLE_TASK);
					}
				}
				
				String cronExpression = request.getParameter("cronExpression");
				if(StringUtils.isNotEmpty(cronExpression)){
					taskDefine.setCronExpression(cronExpression);
				}
				String period = request.getParameter("period");
				if(StringUtils.isNotEmpty(period)){
					taskDefine.setPeriod(Long.valueOf(period));
				}
				String delay = request.getParameter("delay");
				if(StringUtils.isNotEmpty(delay)){
					taskDefine.setDelay(Long.valueOf(delay));
				}
				String startTime = request.getParameter("startTime");
				if(StringUtils.isNotEmpty(startTime)){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");  
				    Date date = null;
					try {
						date = sdf.parse(startTime);
					} catch (ParseException e) {
						e.printStackTrace();
					}  
					taskDefine.setStartTime(date);
				}else{
					taskDefine.setStartTime(new Date());
				}
				String param = request.getParameter("param");
				if(StringUtils.isNotEmpty(param)){
					taskDefine.setParams(param);
				}
				String extKeySuffix = request.getParameter("extKeySuffix");
				if(StringUtils.isNotEmpty(extKeySuffix)){
					taskDefine.setExtKeySuffix(extKeySuffix);
				}
				if(StringUtils.isNotEmpty(cronExpression) || StringUtils.isNotEmpty(period) || null != taskDefine.getStartTime()){
					ConsoleManager.addScheduleTask(taskDefine);
				}
			}
			try {
				List<String> servers = ConsoleManager.getScheduleManager().getScheduleDataManager().loadScheduleServerNames();
				if(servers != null){
			        PrintWriter out = response.getWriter();  
//			        StringBuffer sb = new StringBuffer();
//		    		for(int i=0; i< servers.size();i++){
//		    			String ser = servers.get(i);
//		    			sb.append("<tr class=\"info\">")
//		    			  .append("<td>").append(i+1).append("</td>")
//		    			  .append("<td>").append(ser).append("</td>");
//						if( ConsoleManager.getScheduleManager().getScheduleDataManager().isLeader(ser, servers)){
//							sb.append("<td>").append("是").append("</td>");
//						}else{
//							sb.append("<td>").append("否").append("</td>");
//						}
//		    			sb.append("</tr>");
//		    		}
//		    		
//		    		List<TaskDefine> tasks = ConsoleManager.queryScheduleTask();
//		    		StringBuffer sbTask = new StringBuffer();
//		    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		    		for(int i=0; i< tasks.size();i++){
//		    			TaskDefine taskDefine = tasks.get(i);
//		    			sbTask.append("<tr class=\"info\">")
//		    			  .append("<td>").append(i+1).append("</td>")
//		    			  .append("<td>").append(taskDefine.getTargetMethod4Show()).append("</td>")
//		    			  .append("<td>").append(taskDefine.getParams()).append("</td>")
//		    			  .append("<td>").append(taskDefine.getType()).append("</td>")
//		    			  .append("<td>").append(taskDefine.getThreadNum()).append("</td>")
//		    			  .append("<td>").append(taskDefine.getCronExpression()).append("</td>")
//		    			  .append("<td>").append(taskDefine.getStartTime()).append("</td>")
//		    			  .append("<td>").append(taskDefine.getPeriod()).append("</td>")
//		    			  .append("<td>").append(taskDefine.getDelay()).append("</td>")
//		    			  .append("<td>").append(taskDefine.getCurrentServer()).append("</td>")
//		    			  .append("<td>").append(taskDefine.getStatus()).append("</td>")
//		    			  .append("<td>").append(taskDefine.getRunTimes()).append("</td>")
//		    			  .append("<td>");
//		    			if(StringUtils.isBlank(taskDefine.getPercentage())){
//		    				sbTask.append("-");
//		    			}else{
//		    				sbTask.append(taskDefine.getPercentage());
//		    			}
//		    			sbTask.append("</td>");
//		    			if(taskDefine.getLastRunningTime() > 0){
//		    				Date date = new Date(taskDefine.getLastRunningTime());
//			    			sbTask.append("<td>").append(sdf.format(date)).append("</td>");
//		    			}else{
//		    				sbTask.append("<td>").append("-").append("</td>");
//		    			}
//		    			sbTask.append("<td>");
//		    			if(taskDefine.isStop()){
//		    				sbTask.append("<a href=\"").append(request.getSession().getServletContext().getContextPath())
//			  				 .append("/uncode/schedule2?start=")
//			                 .append(taskDefine.getTargetBean())
//			                 .append("_")
//			                 .append(taskDefine.getTargetMethod());
//		    				if(StringUtils.isNotBlank(taskDefine.getExtKeySuffix())){
//		    					sbTask.append("_").append(taskDefine.getExtKeySuffix());
//		    				}
//		    				sbTask.append("\" style=\"color:green\">运行</a>");
//		    			}else{
//		    				sbTask.append("<a href=\"").append(request.getSession().getServletContext().getContextPath())
//			  				 .append("/uncode/schedule2?stop=")
//			                 .append(taskDefine.getTargetBean())
//			                 .append("_")
//			                 .append(taskDefine.getTargetMethod());
//		    				if(StringUtils.isNotBlank(taskDefine.getExtKeySuffix())){
//		    					sbTask.append("_").append(taskDefine.getExtKeySuffix());
//		    				}
//		    				sbTask.append("\" style=\"color:red\">停止</a>");
//		    			}
//		    			sbTask.append(" <a href=\"").append(request.getSession().getServletContext().getContextPath())
//		    			  				 .append("/uncode/schedule2?del=")
//		    			                 .append(taskDefine.getTargetBean())
//		    			                 .append("_")
//		    			                 .append(taskDefine.getTargetMethod());
//		    			if(StringUtils.isNotBlank(taskDefine.getExtKeySuffix())){
//	    					sbTask.append("_").append(taskDefine.getExtKeySuffix());
//	    				}
//		    			sbTask.append("\" >删除</a>")
//		    			                 .append("</td>");
//						sbTask.append("</tr>");
//		    		}
		    		Map<String, String> rt = new HashMap<>();
		    		rt.put("code", "200");
		 	        out.write(GSON.toJson(rt));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

}
